<template>
  <div :class="{ sticky: isSticky }" class="lc-anchor">
    <ul>
      <li v-for="(item, index) in anchorList" :key="index">
        <a :href="`#${item.id}`" @click.prevent="scrollToAnchor(item.id)">{{
          item.title
        }}</a>
      </li>
    </ul>
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount } from "vue";

const props = defineProps({
  // 锚点列表，包含 id 和 title
  anchorList: {
    type: Array,
    default: () => [],
  },
  // 吸顶的偏移量
  offsetTop: {
    type: Number,
    default: 0,
  },
});

const isSticky = ref(false);

const handleScroll = () => {
  // 获取当前滚动的距离
  const scrollTop = window.pageYOffset || document.documentElement.scrollTop;
  // 根据滚动距离和偏移量判断是否需要吸顶
  isSticky.value = scrollTop >= props.offsetTop;
};

onMounted(() => {
  window.addEventListener("scroll", handleScroll);
});

onBeforeUnmount(() => {
  window.removeEventListener("scroll", handleScroll);
});

const scrollToAnchor = (id) => {
  const element = document.getElementById(id);
  if (element) {
    element.scrollIntoView({ behavior: "smooth" });
  }
};
</script>

<style scoped>
.lc-anchor {
  display: flex;
  background-color: #fff;
  border-bottom: 1px solid #eee;
}

.lc-anchor ul {
  list-style-type: none;
  margin: 0;
  padding: 0;
  display: flex;
}

.lc-anchor li {
  margin: 0 10px;
}

.lc-anchor a {
  text-decoration: none;
  color: #333;
}

.sticky {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 100;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}
</style>
